/*
 *  TCPClientConnectionHandler.c
 *  farfetchproject
 *
 *  Created by Rodrigo Souza on 4/27/10.
 *  Copyright 2010 Unicamp. All rights reserved.
 *
 */

#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdio.h>
#include <netdb.h>
#include <string.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include "ClientProperties.h"

/* Returns the IP address of this host. */
char* getMyIp(){
	char name[80]; /*store my hostname*/
	struct hostent * hostent_ptr;
	int ret;
	
	
	if((ret = gethostname (name, 80)) < 0) {
		perror("*** ERROR: an error occur while getting hostname. ***\n");
		exit(1);
	}
	
	hostent_ptr = gethostbyname(name);
	if(hostent_ptr == NULL) {
		perror("*** ERROR: an error occur while gettin IP. ***\n");
		exit(1);
	}
	
	// h_addr_list contains IPs of this host in network byte order
	// get the first IP
	in_addr_t myIp = ((struct in_addr *)hostent_ptr->h_addr_list[0])->s_addr; 
	
	struct in_addr temp;
	temp.s_addr = myIp;
	
	return inet_ntoa(temp);
}

/* Get socketInfo.  Return: char* = "ip:port". */
char *getClientInfo(int s, struct sockaddr_in *name){
	char *str;	
	socklen_t name_len = sizeof(name);
	if (getsockname(s, (struct sockaddr *) name, &name_len) >= 0){
		// get Socket info
		char port[10];		
		char* strIp = getMyIp();
		sprintf(port,"%d",(int) ntohs(name->sin_port));
		
		// concatenate the strings
		int size = strlen(port)+strlen(strIp)+2;
		str = (char *)malloc(size);
		strcat(str,strIp);
		strcat(str,":");
		strcat(str,port);
		str[size] = '\0';
		
	} else {
		perror("*** ERROR: getSockInfo() error. ***\n");
		exit(1);
		
	}
	
	return str;
}

/* Create the socket. */
int Socket (int family, int type, int flags)	{
	int sockfd;
	
	if ((sockfd = socket(family, type, flags)) < 0) {
		perror("*** ERROR: an error occur while creating a client socket. ***\n");
		exit(1);
		
	} else
		return sockfd;
}


/* Convert the source string in struct family AF_INET. */	
void InetPton (int af, const char *src, void *dst) {
	
	if (inet_pton(af, src, dst) <= 0) {
		perror("*** ERROR: inet_pton error. ***\n");
		exit(1);
	}
	return;
}


/* Start connection with server. */	
void Connect (int sockfd, const struct sockaddr *serv_addr, socklen_t addrlen){
	
	if (connect(sockfd, serv_addr, addrlen) < 0) {
		perror("*** ERROR: connect error. ***\n");
		exit(1);
	}
	return;
}
